import axios from "axios";
import {ResponseErrorBack} from "@/utils/response.error.util";
import setting from "@/setting";
import {_, urlEncode} from "@/utils/common.util";


axios.defaults.timeout = 10000;
axios.defaults.baseURL = setting.API_BASE_URL;


// 添加一个请求拦截器
axios.interceptors.request.use(function (config) {
    // 避免 IE 缓存同一接口地址下的数据
    // config.url += "?" + new Date().getTime();
    if (config.headers['serialize']) {
        config.data = urlEncode(config.data);
    }
    console.log({
        to: config.url,
        method: config.method,
        data: config.data,
        params: config.params,
        config
    });
    return config;
}, function (error) {
    return Promise.reject(error);
});

// 添加一个响应拦截器
axios.interceptors.response.use(function (response) {
    // Do something with response data
    let resp = response.data;
    console[resp.code === 200 ? 'log' : 'error']({
        from: response.config.url,
        method: response.config.method,
        response: resp,
        detail: response,
    });
    try {
        ResponseErrorBack['code' + resp.code](resp, response);
        return Promise.reject(resp);
    } catch (ignore) {
    }
    // mockjs 情况下由于请求瞬间反馈，因此再调试阶段可能会无法看到动画加载情况
    // 因此 特地在此使用延时反馈方式，生产环境下将可设置为 0 或直接返回
    return new Promise(resolve => {
        setTimeout(() => resolve(resp.data), 1000);
    });
}, function (error) {
    // Do something with response error
    if (typeof error !== 'object') {
        // DialogUtil.toast(error, 'error');
    } else {
        // DialogUtil.toast(JSON.stringify(error), 'error');
    }
    console.error(error);
    return Promise.reject(error);
});

export const request = (urlOrOption, option = {}) => {
    if (_.isObject(urlOrOption)) {
        return axios(urlOrOption);
    }
    if (_.isString(urlOrOption)) {
        let opt = Object.assign({
            url: urlOrOption,
        }, option);
        return {
            get(params) {
                return axios({...opt, method: 'get', params});
            },
            post(data) {
                return axios({...opt, method: 'post', data})
            }
        }
    }
    return axios;
};



